<template>
  <el-form-item :label="label" :prop="prop">
    <el-upload
      action=""
      :list-type="ListType(type)"
      :accept="acceptFile"
      :multiple="multiple"
      :limit="limitNum"
      :auto-upload="false"
      :on-exceed="handleExceed"
      :before-upload="beforeUpdata"
      :on-change="handleChange"
      :file-list="uploadFileList"
      :class="{ hide: hideUpload }"
    >
      <template #default>
        <el-button v-if="![1, 2, 3, 6].includes(type)" type="text" :plain="uploadName">{{ uploadName || '上传文件' }}</el-button>
        <el-button v-if="[6].includes(type)" :plain="uploadName">{{ uploadName || '上传文件' }}</el-button>
        <el-icon v-if="[1, 2, 3].includes(type)" class="upload_icon" >
          <plus />
          <div class="upload_icon_text">点击上传</div>
        </el-icon>
        <!-- 添加插槽 -->
        <slot></slot>
      </template>
      <template #file="{ file }" v-if="![4, 5, 6].includes(type)">
        <div class="file_upload_box">
          <el-image style="el-upload-list__item-actions" :src="file.url" fit="cover"> </el-image>
          <el-icon class="del_icon" @click="handleRemove(file)"><DeleteFilled /></el-icon>
        </div>
      </template>
      <template #tip>
        <div class="el-upload__tip">
          <span v-if="type == 1">文件格式支持DOC、DOCX、XLS、XLSX、PPT、PPTX、PDF格式，文件大小不超过20M；单张图片大小不超过2M，支持png、jpg、gif等格式</span>
        </div>
      </template>
    </el-upload>
  </el-form-item>
</template>
<script setup lang="ts">
  import { ref, reactive, defineProps, onUnmounted, computed } from 'vue'
  import { ElForm, ElMessage } from 'element-plus'
  import type { UploadProps, UploadUserFile } from 'element-plus'
  import { Plus, ZoomIn, Download, Delete } from '@element-plus/icons-vue'
  import { uploadFile2 } from '@/api/common'
  import { getSetionId, getImage_wh, getSuffixIcon, IsNotEmpty } from '@/utils/utils'
  import bus from '@/utils/bus'
  const emit = defineEmits(['submit'])

  const formRef = ref<InstanceType<typeof ElForm>>()
  const dialogImageUrl = ref('')
  const dialogVisible = ref(false)
  const uploadFileList = ref<UploadUserFile[]>([])
  const ListType = (val: number) => {
    switch (val) {
      case 1:
      case 2:
      case 3:
        return 'picture-card'
      case 4:
        return 'text'
      default:
        return 'text'
    }
  }
  const props = defineProps<{
    upInfo: {
      type: number //文件类型
      label: string //文件名称
      prop: string // 是否是必传
      files: any //文件
      multiple: {
        //是否支持多选
        type: boolean
        default: false
      }
      limitSize: number // 最大文件上传限制
      limitNum: {
        // 上最大传数量
        type: number
        default: 9
      }
      uploadName: ''
      acceptFile: string // 上传类型文件判断
    }
  }>()
  //  type: 1 图片  2 文件 3 视频 4 语音 5 Excell
  const { type, label, prop, files, multiple, limitSize, acceptFile, limitNum, uploadName } = props.upInfo
  const beforeUpdata = async (file: any) => {
    const fileType = file.name.substring(file.name.lastIndexOf('.'))
    let isPic = 1
    if(fileType == '.png'||fileType == '.jpg'||fileType == '.gif'){
      isPic = 1
    }else if(fileType == '.doc'||fileType == '.docx'||fileType == '.xls'||fileType == '.ppt'||fileType == '.pptx'||fileType == '.pdf'||fileType == '.xlsx'){
      isPic = 2
    }else{
      isPic = 3
    }
    let tips = '图片'
    switch (isPic) {
      case 1:
        tips = '图片'
        const is2M = file.size / 1024 / 1024 <= limitSize
        if (!is2M) {
          ElMessage.warning(`上传的${tips}最大支持${limitSize}M`)
          handleRemove(file)
          return false
        }
        let ext = file.name.substring(file.name.lastIndexOf('.'))
        const isImge = acceptFile.indexOf(ext) == -1
        if (isImge) {
          ElMessage.warning(`该图片是${ext}格式,请上传${acceptFile}格式图片`)
          handleRemove(file)
          return false
        }
        break
      case 2:
        tips = '文件'
        const fileSize = file.size / (1024*1024)
        console.log('fileSize: ', fileSize);
        if(fileSize>20){
          ElMessage.warning('上传的文件最大支持20M')
          handleRemove(file)
          return false
        }
        break
      case 3:
        ElMessage.warning('请上传符合要求的文件类型')
        return false
        break

    }
    return true
  }
  // 上传文件
  let ext = ref()
  const uploadImg = async (file: any) => {
    file = file.raw
    ext.value = file.name.substring(file.name.lastIndexOf('.'))
    let flag = await beforeUpdata(file)
    if (!flag) return
    return await uploadFile2({
    file,
    fileName: file.name
    })
  }
  const hideUpload = computed(() => {
    return uploadFileList.value.length >= limitNum
  })
  const handleRemove = (file: any) => {
    if (file.url) {
      uploadFileList.value = uploadFileList.value.filter((item: any) => item.name != file.name)
    }
    emit('submit', uploadFileList.value)
  }
  // 上传改变
  const handleChange = async (file: any, list: any) => {
    const data: any = await uploadImg(file)
    if (IsNotEmpty(data)) {
      const last = data.url.substring(data.url.lastIndexOf('.'))
      if (last == '.png'||last == '.jpg'||last == '.gif') {
        uploadFileList.value.push(data)
      } else {
        uploadFileList.value.push({
          realurl: data.url,
          code: data.code,
          url: getSuffixIcon(data.url),
          name: file.name
        })
        uploadFileList.value = uploadFileList.value.map(el => el)
      }
      console.log('---1', file, list);
      emit('submit', uploadFileList.value)
    }else{
      list.pop()
      return
    }
  }

  const handleExceed = (file: any, list: any) => {
    ElMessage.warning(`当前限制选择 ${limitNum} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + list.length} 个文件`)
  }
  // 图片数据回显
  const echo = (data: any, isFllow?: any) => {
    if (!isFllow) {
      if (type == 1) {
        if (data.cover_image_url) {
          uploadFileList.value.push({ url: data.cover_image_url })
        } else {
          data.forEach((item: any) => {
            uploadFileList.value.push({ url: item.absolute_url })
          })
        }
      } else if (type == 4) {
        uploadFileList.value.push({ name: data.title, url: '/static/file/mp3.png' })
      }
    } else {
      if (data.length > 0) {
        uploadFileList.value = []
        data.forEach((item: any) => {
          if (item.type == 1) {
            uploadFileList.value.push({ url: item.url, code: item.code, name: item.name })
          } else {
            uploadFileList.value.push({ url: getSuffixIcon(item.url), code: item.code, name: item.name })
          }
        })
      }
    }
    return
  }
  // 清空数据回显
  const empty = () => {
    uploadFileList.value = []
  }
  bus.on('echo', echo)
  bus.on('empty', empty)
  const handlePictureCardPreview = (file: any) => {
    dialogImageUrl.value = file.url!
    dialogVisible.value = true
  }
  // 下载
  const handleDownload = (file: any) => {}
  // 主动暴露方法
  defineExpose({ empty, echo })
  onUnmounted(() => {
    bus.off('echo', echo)
    bus.off('empty', empty)
  })
</script>
<style lang="scss" scoped>
  .pre_img_box {
    overflow: hidden;
    .pre_image {
      display: block;
      margin: auto;
      max-height: 400px;
    }
  }
  :deep(.el-upload--picture-card) {
    width: 110px;
    height: 110px;
    .upload_icon {
      display: initial;
      width: 110px;
      height: 110px;
      text-align: center;
      font-size: 20px;
      color: #ff6b00;
      .icon {
        margin-top: 30px;
      }
      .upload_icon_text {
        font-style: normal;
        margin-top: 12px;
        font-size: 14px;
      }
    }
  }
  :deep .el-upload-list__item {
    width: 110px;
    height: 110px;
    display: inline-block;
    .file_upload_box {
      position: relative;
      width: 100%;
      height: 100%;
      .del_icon {
        position: absolute;
        right: 10px;
        top: 10px;
        cursor: pointer;
      }
    }
  }
  .el-upload__tip {
    font-size: 12px;
    line-height: 18px
  }
</style>
<style>
  .hide .el-upload--picture-card {
    display: none;
  }
  .upload_icon {
    width: 140px;
    height: 90px;
  }
</style>
  